package cn.lhf.cd;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

public class Main {
    private static DataSource dataSource;
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 初始化数据源
     */
    private static void initDataSource() throws Exception {
        Properties dbConfig = new Properties();
        InputStream dbConfigStream = Main.class.getResourceAsStream("/db-config.properties");
        if (dbConfigStream == null)
            throw new Exception("未能载入数据库配置文件");
        dbConfig.load(dbConfigStream);
        dbConfigStream.close();
        dataSource = DruidDataSourceFactory.createDataSource(dbConfig);
    }

    /**
     * 初始化mybatis
     */
    private static void initSqlSessionFactory() {
        Environment environment = new Environment("development", new JdbcTransactionFactory(), dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMappers("cn.lhf.cd.mapper");

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

    /**
     * 获取SQLSession工厂类实例
     * @return SQLSession工厂类实例
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    /**
     * 打开一个SQLSession
     * @return SQLSession
     */
    public static SqlSession openSqlSession() {
        return sqlSessionFactory.openSession();
    }

    public static void main(String[] args) {
        try {
            initDataSource();
            initSqlSessionFactory();
            FXApplication.launch(FXApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
